const crypto = require('crypto')
import dayjs from 'dayjs'
import _ from 'lodash'

export function md5(str) {
  return crypto
    .createHash('md5')
    .update(str)
    .digest('hex')
}

export function pageModel(pageData, pageIndex, pageSize) {
  const totalPages = Math.ceil(pageData.count / pageSize)
  return {
    pageIndex,
    pageSize,
    totalCount: pageData.count,
    totalPages,
    hasMore: pageIndex + 1 < totalPages,
    rows: pageData.rows
  }
}

export const aesDecrypt = (key, iv, crypted) => {
  crypted = new Buffer(crypted, 'base64')
  key = new Buffer(key, 'base64')
  iv = new Buffer(iv, 'base64')
  const decipher = crypto.createDecipheriv('aes-128-cbc', key, iv)
  let decoded = decipher.update(crypted, 'base64', 'utf8')
  decoded += decipher.final('utf8')
  return decoded
}

export const sha1 = message => {
  return crypto
    .createHash('sha1')
    .update(message, 'utf8')
    .digest('hex')
}

export const genNo = (randLen = 6) => {
  let cd = dayjs().format('YYYYMMDDHHmmss')
  let rs = 'QWERTYUIOPASDFGHJKLZXCVBNM'
  let t = []
  for (let i = 1; i <= randLen; i++) {
    let rn = _.random(0, rs.length - 1)
    t.push(rs[rn])
  }
  return cd + t.join('')
}
